import { defineComponent, reactive, ref, toRefs } from 'vue'
import { Card, Form, type FormInstance, FormItem, Input, Modal } from 'ant-design-vue'
const UpdatePassword = defineComponent({
  name: 'UpdatePassword',
  props: {
    userCode: {
      type: [String],
      required: false
    },
    username: {
      type: [String],
      required: false
    },
    show: {
      type: Boolean
    }
  },
  emits: ['cancelModal', 'confirmModal'],
  setup(props, ctx) {
    const state = reactive({
      detailFormRef: ref<FormInstance | null>(null),
      detailForm: {
        password: ''
      },
      rules: {
        password: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: ['blur', 'change'] },
          { pattern: /^[a-zA-Z0-9_-]{6,16}$/, message: '密码只支持字母、数字和下划线', trigger: ['blur', 'change'] }
        ]
      }
    })

    const handleConfirm = async () => {
      try {
        const values = state.detailFormRef && (await state.detailFormRef.validateFields())
        if (values) {
          ctx.emit('confirmModal', props.userCode, state.detailForm.password)
        }
      } catch (errorInfo) {
        console.log('Failed:', errorInfo)
      }
    }

    const handleCancel = () => {
      ctx.emit('cancelModal')
    }
    return { ...toRefs(props), ...toRefs(state), handleCancel, handleConfirm }
  },

  render() {
    const { show, username, detailForm, rules, handleCancel, handleConfirm } = this
    return (
      <>
        <Modal
          open={show}
          title='修改密码'
          width='600px'
          okText='确定'
          cancelText='取消'
          onCancel={handleCancel}
          onOk={handleConfirm}
        >
          <Card>
            <Form ref='detailFormRef' model={detailForm} rules={rules} style={{ width: '80%' }}>
              <FormItem label='员工姓名' name='username'>
                <span>{username}</span>
              </FormItem>
              <FormItem label='新密码' name='password'>
                <Input v-model={[detailForm.password, 'value']} showCount maxlength={32} placeholder='请输入新密码' />
              </FormItem>
            </Form>
          </Card>
        </Modal>
      </>
    )
  }
})
export default UpdatePassword
